import 'whatwg-fetch'
import { message } from 'antd'
import { helper, config } from './'

/**
 * 包装`fetch`包括获取`jsonp`
 * 参见 npm package whatwg-fetch fetch-jsonp
 * @param  {[string]}  url     [description]
 * @param  {[object]}  options [description]
 * @param  {Boolean}   jsonp   [description]
 * @return {Promise}
 */
function myFetch(url, { method = 'GET', body = '' } = {}) {
  let options = {
    method,
    body,
  }

  if (['POST', 'PUT'].includes(method)) {
    options.headers = {
      'Content-Type': 'application/json',
    }
  }

  url = config.rootApi + url

  const promise = (method !== 'GET') ? fetch(url, options) : fetch(url)

  return promise.then(res => res.json())
    .then(json => {
      if (!json.error) {
        return json
      }
      else {
        message.error(json.message)
        console.log(json)
        return
      }
    })
    .catch(err => helper.onPromiseError(err))
}

export default myFetch